//
//  NRLSVMTViewController.m
//  NaRiLSVMT
//
//  Created by jmsre on 14-8-8.
//  Copyright (c) 2014年 helloyouth.org. All rights reserved.
//

#import "NRLSVMTViewController.h"
#import "UIViewController+MJPopupViewController.h"
#import "SettingViewController.h"
#import "MBProgressController.h"
#import "NRLSVMTViewController+Request.h"
#import <CommonCrypto/CommonDigest.h>
#import "MBProgressController.h"
#import "Network_Operation.h"
#import "Base64.h"
#import "FileManager.h"


NSTimeInterval  oldCurrentTime =0;


@interface NRLSVMTViewController ()<SettingPopupDelegate,UITextFieldDelegate>
{
    SettingViewController *settingViewController;
}

@end

@implementation NRLSVMTViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.loginFirstView.layer.shadowOffset = Size(0, 3.0);
    self.loginFirstView.layer.shadowOpacity =1.0;
    self.loginFirstView.layer.shadowRadius = 7.0;
    self.loginFirstView.layer.shadowColor = [UIColor blackColor].CGColor;
    //用于写用户名和登录信息缓存:
    self.dLoginInfofm = [NSFileManager defaultManager];
    self.dLoginInfopath = [NSString stringWithFormat:@"%@%@%@",[FileManager getLibraryDirectory],@"/",@"LoginInfo.plist"];
    //用于写密码信息缓存:
    self.dLoginInfo_PassWordfm = [NSFileManager defaultManager];
    self.dLoginInfo_PassWordpath = [NSString stringWithFormat:@"%@%@%@%@%@",[FileManager getLibraryDirectory],@"/",@"LoginInfo",@"_PassWord",@".plist"];
    
    /**************读本地登录缓存*********************************/
    if(YES == [self.dLoginInfofm fileExistsAtPath:self.dLoginInfopath])
    {
        NSData *data = [NSData dataWithContentsOfFile:self.dLoginInfopath];
        NSMutableDictionary *dicLoginInfo = [NSMutableDictionary dictionaryWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithData:data]];
        
        self.userNameText.text = [dicLoginInfo objectForKey:@"userNameText"];
//        self.userPassword.text = [dicSetupInfo objectForKey:@"userPassword"];
    }
    if(YES == [self.dLoginInfo_PassWordfm fileExistsAtPath:self.dLoginInfo_PassWordpath])
    {
        NSData *data = [NSData dataWithContentsOfFile:self.dLoginInfo_PassWordpath];
        NSMutableDictionary *dicLoginInfo = [NSMutableDictionary dictionaryWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithData:data]];
        
//        self.userNameText.text = [dicSetupInfo objectForKey:@"userNameText"];
        self.userPassword.text = [dicLoginInfo objectForKey:@"userPassword"];
    }
    /***********************************************************/
    
    self.userNameText.delegate = self;
    self.userPassword.delegate = self;
    
    //响应键盘通知:
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardHide:)
                                                 name:UIKeyboardWillHideNotification
                                                object:nil];
    //uuid是否合法
    [self testUuidlaw];
    
    [AddNoticeObserver(NoticeKey_DeviceResigner){
        [self deviceisRegister:1];

    }];
}
-(void)viewWillAppear:(BOOL)animated
{
//    //uuid是否合法
//    [self testUuidlaw];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)jumpToMainUI:(id)sender {
//    self.navigationController.navigationBar.hidden = NO;
//    NRLSVMTSubjectViewController *subjectViewController = [[NRLSVMTSubjectViewController alloc] initWithNibName:@"NRLSVMTSubjectViewController" bundle:nil];
//    [self.navigationController pushViewController:subjectViewController animated:YES];
//    return;
    [self.loginFirstView endEditing:YES];
    
    if(testConnectSucess == NO)
    {
        [[MBProgressController sharedInstance] showTipsOnlyText:@"网络不可用"
                                                       AndDelay:1.5];
        [[MBProgressController sharedInstance] hide];
        return;
    }
    //获取UUID
    NSDictionary  *dic = [NSDictionary dictionaryWithObjectsAndKeys:[self md5_base64:self.userNameText.text] ,@"userName",[self md5_base64:self.userPassword.text],@"userPassword",[self setKeyChainValue]/*@"0401B100-86F2-4D62-BAAC-53E5C3E69E77"*/,@"uuId",nil];
    
    [[User sharedInstance] installgUser:dic];
    
    if([self.userNameText.text isEqualToString:@""])
    {
        NSLog(@"用户名为空");
        [[MBProgressController sharedInstance] showTipsOnlyText:@"用户名为空"
                                                       AndDelay:1.5];
        [[MBProgressController sharedInstance] hide];
        return;
    }
    if([self.userPassword.text isEqualToString:@""])
    {
        NSLog(@"密码为空");
        [[MBProgressController sharedInstance] showTipsOnlyText:@"密码为空"
                                                       AndDelay:1.5];
        [[MBProgressController sharedInstance] hide];
        return;
    }
    
    [self NRLSMTUserLogin];//进行登录连接
}

- (IBAction)setupInTopAction:(id)sender {
    [self.loginFirstView endEditing:YES];
    settingViewController = nil;
    settingViewController = [[SettingViewController alloc] initWithNibName:@"SettingViewController" bundle:nil];
    settingViewController.delegate = self;
    settingViewController.isLogin = NO;
    [self presentPopupViewController:settingViewController animationType:MJPopupViewAnimationFade];
}

#pragma mark-
#pragma mark- SettingPopupDelegate

- (void)backButtonClicked:(SettingViewController *)setupViewController
{
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
    settingViewController = nil;
}

#pragma mark-
#pragma mark- UITextFieldDelegate

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if(textField == self.userNameText)
    {
        self.userPassword.text = @"";
        [self.dLoginInfofm removeItemAtPath:self.dLoginInfopath error:nil];
        [self.dLoginInfo_PassWordfm removeItemAtPath:self.dLoginInfo_PassWordpath error:nil];
    }
    else if (textField == self.userPassword)
    {
        [self.dLoginInfo_PassWordfm removeItemAtPath:self.dLoginInfo_PassWordpath error:nil];
    }
    return YES;
}

#pragma mark -
#pragma mark -md5 算法加密
-(NSString *)md5_base64:(NSString *)str{
    const char *cStr = [str UTF8String];
    //    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    //    CC_MD5(cStr,strlen(cStr),digest);
    
    //NSData *base64 =[[NSData alloc]initWithBytes:cStr length:CC_MD5_DIGEST_LENGTH];
    NSData *base64 = [[NSData alloc] initWithBytes:cStr length:(strlen(cStr))];
    base64 =[Base64 encodeData:base64];
    
    NSString *output = [[NSString alloc]initWithData:base64 encoding:NSUTF8StringEncoding];
    NSLog(@"%@",output);
    return output;
}

//背景响应键盘按钮:
- (IBAction)topButAction:(id)sender {
    //[self.loginFirstView resignFirstResponder];
    [self.loginFirstView endEditing:YES];
}

- (IBAction)leftButAction:(id)sender {
    //[self.loginFirstView resignFirstResponder];
    [self.loginFirstView endEditing:YES];
}

- (IBAction)rightButAction:(id)sender {
    //[self.loginFirstView resignFirstResponder];
    [self.loginFirstView endEditing:YES];
}

- (void)keyboardShow:(NSNotification *)note {
    self.reInputName = YES;
    
    if(self.loginFirstView.frame.origin.y <= 100)
    {
        return;
    }
    
    [self.loginFirstView setFrame:CGRectMake(self.loginFirstView.frame.origin.x, self.loginFirstView.frame.origin.y-100, self.loginFirstView.frame.size.width, self.loginFirstView.frame.size.height)];
    [self.loginFirstImageView setFrame:CGRectMake(self.loginFirstImageView.frame.origin.x, self.loginFirstImageView.frame.origin.y-100, self.loginFirstImageView.frame.size.width, self.loginFirstImageView.frame.size.height)];
}

- (void)keyboardHide:(NSNotification *)note {
    
    if(self.loginFirstView.frame.origin.y >= 200)
    {
        return;
    }
    
    [self.loginFirstView setFrame:CGRectMake(self.loginFirstView.frame.origin.x, self.loginFirstView.frame.origin.y+100, self.loginFirstView.frame.size.width, self.loginFirstView.frame.size.height)];
    [self.loginFirstImageView setFrame:CGRectMake(self.loginFirstImageView.frame.origin.x, self.loginFirstImageView.frame.origin.y+100, self.loginFirstImageView.frame.size.width, self.loginFirstImageView.frame.size.height)];
}
-(void)testUuidlaw
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *getScreenStr = [Network_API Network_API_GetScreen];
        NSString *uuid = [self setKeyChainValue];
        AFHTTPClient *httpClient = [Network_Operation httpClientWithUrl:getScreenStr];
        NSDictionary *dic = @{
                              @"classname":@"iPadSettingService",
                              @"methodname":@"deviceAccess",
                              @"parameterClasss":@[@{
                                                       @"parametername" :@"uuid",
                                                       @"parametervalue":uuid,
                                                       @"valuetype":@"java.lang.String"}
                                                   ]
                              };
        [httpClient postPath:getScreenStr parameters:@{@"jsonstr":[Common dictoJson:dic],
                                                       @"callback":@""
                                                       }
                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                         NSString *tmpstr = responseObject;
                         NSString *strr = [tmpstr substringFromIndex:1];
                         NSString *str = [strr substringToIndex:1];
                         //NSString *strpp = [str substringFromIndex:1];
                         dispatch_async(dispatch_get_main_queue(), ^{
                             [self deviceisRegister:[str intValue]];
                         });
                     }
                     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                         [self deviceisRegister:0];
                     }];
        
    });//
}
-(void)deviceisRegister:(NSInteger)flag
{
    NSString *uuid = [self setKeyChainValue];
    if(flag){
        self.uuidLab.textColor = [UIColor blackColor];
        CGRect r = self.uuidLab.frame;
        r.origin.x = 470;
        self.uuidLab.frame = r;
        self.uuidLab.text = [NSString stringWithFormat:@"设备已注册"];
    }
    else{
        self.uuidLab.textColor = [UIColor redColor];
//        self.uuidLab.text = [NSString stringWithFormat:@"设备未注册,请联系可视化平台管理员注册设备(%@)",uuid];
        self.uuidLab.text = [NSString stringWithFormat:@"设备未注册,请注册设备(%@)",uuid];

    }
}
@end
